import type { Config } from './config.interface';

const configuration = (): Config => {
  // 确保必需的环境变量存在
  const requiredEnvVars = [
    'DB_USERNAME',
    'DB_PASSWORD',
    'DB_DATABASE',
    'JWT_SECRET',
  ];
  for (const envVar of requiredEnvVars) {
    if (!process.env[envVar]) {
      throw new Error(`缺少必需的环境变量: ${envVar}`);
    }
  }

  const nodeEnv = process.env.NODE_ENV || 'development';
  if (!['development', 'production', 'test'].includes(nodeEnv)) {
    throw new Error('NODE_ENV 必须是 development、production 或 test');
  }

  const config = {
    app: {
      nodeEnv: nodeEnv as 'development' | 'production' | 'test',
      port: parseInt(process.env.PORT || '3000', 10),
    },
    database: {
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT || '3306', 10),
      username: process.env.DB_USERNAME!,
      password: process.env.DB_PASSWORD!,
      database: process.env.DB_DATABASE!,
    },
    jwt: {
      secret: process.env.JWT_SECRET!,
      expiresIn: process.env.JWT_EXPIRES_IN || '24h',
    },
    upload: {
      path: process.env.UPLOAD_PATH || './uploads',
      maxSize: parseInt(process.env.UPLOAD_MAX_SIZE || '5242880', 10),
    },
  } as const;

  return config;
};

export default configuration;
